package com.yidushishizijie;

/*
 * 两线程，操作初始值为零的的一个变量，
 * 实现一个线程对该变量加1，一个线程对该变量减1
 * 实现交替，来十轮；
 * */

class AirConditioner02{
    private int number = 0;

    public synchronized void increase() throws InterruptedException {
        //判断
        while (number != 0){
            this.wait();
        }
        //操作
        number++;
        System.out.println(Thread.currentThread().getName()+"\t"+number);
        //通知
        this.notifyAll();
    }

    public synchronized void decrease() throws InterruptedException {
        //判断
        while (number == 0){
            this.wait();
        }
        //操作
        number--;
        System.out.println(Thread.currentThread().getName()+"\t"+number);
        //通知
        this.notifyAll();
    }
}
public class ThreadWaitNodifyReview{
    public static void main(String[] args) {
        AirConditioner02 airConditioner02 = new AirConditioner02();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    airConditioner02.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    airConditioner02.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    airConditioner02.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    airConditioner02.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}
